<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>客户端页面</title>
  <style>
    span {
      padding: 0 16;
    }
  </style>
</head>
<body>
  <button class="btn">连接服务器</button>

  <button class="send">发送消息</button>

  <button class="receiveOrder">接收订单数据</button>
  <div class="orders"></div>

  <script>
    /* 处理实时接收订单信息 */
    document.querySelector('.receiveOrder').addEventListener('click', () => {
      const ws = new WebSocket('ws://localhost:8080')
      ws.onmessage = event => {
        const order = JSON.parse(event.data)
        const html = Object.keys(order).map(key => {
          const html = `
            <span>${key}: ${order[key]}</span>
          `
          return html
        }).join('')
        document.querySelector('.orders').innerHTML += `
          <div>${html}</div>
        `
      }
    })
  </script>

  <script>
    let ws
    
    document.querySelector('.btn').addEventListener('click', () => {
      // 创建 WebSocket 对象
      ws = new WebSocket('ws://localhost:8080')
      // 注册事件监听
      ws.addEventListener('open', () => {
        console.log('建立连接...')
      })

      // message 事件，用于接收服务端发送的消息
      ws.addEventListener('message', (event) => {
        console.log('接收到服务端的消息:', event)
      })
    })

    document.querySelector('.send').addEventListener('click', () => {
      // 调用 WebSocket 对象的 send() 方法，向服务端发送消息
      ws.send('数据:' + Math.random().toString(16))
    })
  </script>
</body>
</html>